var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var shopManageRouter = require('./routes/shopManage');
var imagesRouter = require('./routes/images');

const proxy = require('http-proxy-middleware');
const options = {
	target: 'http://localhost:8080',  // 目标服务器的 host
	changeOrigin: true,               // 默认 false，是否需要改变原始主机头为目标 URL
	pathRewrite: {                    // 重写请求
		'^/api': '/',                   // 所有以 "/api" 开头的请求，"/api" 都会重写为 "/"
	}
}

//		配置session
const session = require('express-session');
const FileStore = require('session-file-store')(session);

var app = express();



// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use('/api', proxy(options));   // proxy(options) 即创建代理


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//		配置session
app.use(session({
	name: 'identityKey',
	secret: 'chyingp', // ⽤来对session id相关的cookie进⾏签名
	store: new FileStore(), // 本地存储session（⽂本⽂件，也可以选择其他store，⽐如redis的）
	saveUninitialized: false, // 是否⾃动保存未初始化的会话，建议false
	resave: false, // 是否每次都重新保存会话，建议false
	cookie: {
		maxAge: 1000 * 60*60 // 有效期，单位是毫秒
	}
}));






app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/shopManage', shopManageRouter);
app.use('/images', imagesRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
	next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
	// set locals, only providing error in development
	res.locals.message = err.message;
	res.locals.error = req.app.get('env') === 'development' ? err : {};

	// render the error page
	res.status(err.status || 500);
	res.render('error');
});

// module.exports = app;
app.listen('3001', function () {
	console.log("目标服务器3001 端口启动成功");
})